import COS, {
  type GetAuthorizationOptions,
  type GetAuthorizationCallbackParams,
} from "cos-js-sdk-v5";
import { format } from "date-fns";
import { get as getVal } from "svelte/store";
import { getStsCredential } from "../api/cos";
import { stsCredential$ } from "../store/entity/cos/StsCredential";
import { v4 as uuid } from "uuid";

export const getAuthorization = (
  options: GetAuthorizationOptions,
  callback: (
    /** params 回传给 SDK 的签名或获取临时密钥 */
    params: GetAuthorizationCallbackParams
  ) => void
) => {
  let $stsCredential$ = getVal(stsCredential$);
  console.log("getAuthorization =>", $stsCredential$);
  callback({
    /** 临时密钥 tmpSecretId */
    TmpSecretId: $stsCredential$.tmp_secret_id,
    /** 临时密钥 tmpSecretKey */
    TmpSecretKey: $stsCredential$.tmp_secret_key,
    SecurityToken: $stsCredential$.session_token, // 如果使用临时密钥，需要传 SecurityToken
    StartTime: $stsCredential$.start_time,
    ExpiredTime: $stsCredential$.expired_time,
  });
};

const cos = new COS({
  getAuthorization,
  UploadCheckContentMd5: true,
});

export const uploadCosFile = async (fileName: string, body: COS.UploadBody) => {
  let $stsCredential$ = getVal(stsCredential$);
  if ($stsCredential$.expired_time === 0) {
    const stsCredential = await getStsCredential();
    stsCredential$.set(stsCredential);
    $stsCredential$ = getVal(stsCredential$);
  }
  let idx = fileName.lastIndexOf(".");
  let fileType = fileName.substring(idx + 1);
  let baseName = fileName.substring(0, idx);
  const key = `${format(
    new Date(),
    "yyyyMMddHH"
  )}/${baseName}_${uuid()}.${fileType}`;
  console.log("$stsCredential$=>", $stsCredential$);
  const putRet = await cos
    .putObject({
      /* 必须 */
      Bucket: $stsCredential$.bucket,
      /* 存储桶所在地域，必须字段 */
      Region: $stsCredential$.region,
      /* 必须 */
      Key: key,
      StorageClass: "STANDARD",
      Body: body, // 上传文件对象
      onProgress: function (progressData) {
        console.log(JSON.stringify(progressData));
      },
    })
    .catch((err) => {
      throw err;
    });

  return {
    ...putRet,
    key: `/${key}`,
  };
};
